package com.btjava.maven.pomver.window;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.btjava.maven.pomver.data.CommonData;
import com.btjava.maven.pomver.handler.PomXmlHandler;
import com.btjava.maven.pomver.handler.WorkSpaceXmlHandler;
import com.btjava.maven.pomver.utils.HTTPTools;
import com.btjava.maven.pomver.utils.NoticUtils;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MessageType;
import com.intellij.ui.EditorTextField;
import org.apache.commons.lang.StringUtils;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.VerticalLayout;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MavenDiaLog extends DialogWrapper {

    private JLabel masterLabel;
    private JLabel snapshotLabel;
    private EditorTextField majorMasterLabel;
    private EditorTextField majorSnapshotLabel;
    private EditorTextField minorMasterLabel;
    private EditorTextField minorSnapshotLabel;
    private EditorTextField revisedMasterLabel;
    private EditorTextField revisedSnapshotLabel;

    public MavenDiaLog() {
        super(true);
        setTitle("maven版本管理工具");
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new VerticalLayout());
        //地址栏
        JPanel mavenPanel = new JPanel();
        JLabel mavenTips = new JLabel("maven地址:");
        mavenTips.setPreferredSize(new Dimension(75,30));
        mavenPanel.add(mavenTips);
        String[] urls = new String[CommonData.urlList.size()];
        CommonData.urlList.toArray(urls);
        JComboBox combobox = new JComboBox(urls);
        combobox.setPreferredSize(new Dimension(425,30));
        combobox.setEditable(true);
        mavenPanel.add(combobox);
        jPanel.add(mavenPanel);

        JPanel projectPanel = new JPanel();
        JLabel projectTips = new JLabel("项目:");
        projectTips.setPreferredSize(new Dimension(75,30));
        EditorTextField artifactId = new EditorTextField(CommonData.artifactId);
        artifactId.setPreferredSize(new Dimension(300,30));
        JButton refresh = new JButton("刷新");
        refresh.setPreferredSize(new Dimension(123,30));
        refresh.addActionListener(e->{
            String url = Objects.nonNull( combobox.getSelectedItem())?combobox.getSelectedItem().toString():"";
            String artifactIdValue = artifactId.getText();
            getSouthPanel(url,artifactIdValue);
        });
        projectPanel.add(projectTips);
        projectPanel.add(artifactId);
        projectPanel.add(refresh);
        jPanel.add(projectPanel,BorderLayout.CENTER);
        //表格部分
        String url = Objects.nonNull( combobox.getSelectedItem())?combobox.getSelectedItem().toString():"";
        String artifactIdValue = artifactId.getText();
        JPanel southPanel =new JPanel();
        southPanel.setPreferredSize(new Dimension(500,260));
        JPanel titlePanel = new JPanel();
        JLabel nulLabel = new JLabel("");
        JLabel master = new JLabel("master");
        JLabel snapshot = new JLabel("snapshot");
        nulLabel.setPreferredSize(new Dimension(100,30));
        master.setPreferredSize(new Dimension(200,30));
        master.setHorizontalAlignment(SwingConstants.CENTER);
        snapshot.setPreferredSize(new Dimension(200,30));
        snapshot.setHorizontalAlignment(SwingConstants.CENTER);
        titlePanel.add(nulLabel);
        titlePanel.add(master);
        titlePanel.add(snapshot);
        titlePanel.setLayout(new HorizontalLayout());
        JPanel curPanel = new JPanel();
        JLabel curLabel = new JLabel("当前版本:");
        curLabel.setPreferredSize(new Dimension(100,30));
        this.masterLabel = new JLabel("");
        this.masterLabel.setPreferredSize(new Dimension(200,30));
        this.masterLabel.setHorizontalAlignment(SwingConstants.CENTER);
        this.snapshotLabel = new JLabel();
        this.snapshotLabel.setPreferredSize(new Dimension(200,30));
        this.snapshotLabel.setHorizontalAlignment(SwingConstants.CENTER);
        curPanel.add(curLabel);
        curPanel.add(this.masterLabel);
        curPanel.add(this.snapshotLabel);
        JPanel referencePanel = new JPanel();
        JLabel referenceLabel = new JLabel("推荐版本号：");
        referenceLabel.setPreferredSize(new Dimension(500,30));
        referenceLabel.setHorizontalAlignment(SwingConstants.LEFT);
        referencePanel.add(referenceLabel);
        //主版本
        JPanel majorPanel = new JPanel();
        JLabel majorTag = new JLabel("主版本：");
        majorTag.setPreferredSize(new Dimension(100,30));
        majorTag.setHorizontalAlignment(SwingConstants.CENTER);
        this.majorMasterLabel = new EditorTextField("");
        this.majorMasterLabel.setPreferredSize(new Dimension(130,30));

        JButton majorMasterBtn = new JButton("应用");
        majorMasterBtn.setPreferredSize(new Dimension(70,30));
        majorMasterBtn.addActionListener(e->{
            saveVersion(this.majorMasterLabel.getText());
        });

        this.majorSnapshotLabel = new EditorTextField();
        this.majorSnapshotLabel.setPreferredSize(new Dimension(130,30));

        JButton majorSnapshotBtn = new JButton("应用");
        majorSnapshotBtn.setPreferredSize(new Dimension(70,30));
        majorSnapshotBtn.addActionListener(e->{
            saveVersion(this.majorSnapshotLabel.getText());
        });

        majorPanel.add(majorTag);
        majorPanel.add(this.majorMasterLabel);
        majorPanel.add(majorMasterBtn);
        majorPanel.add(this.majorSnapshotLabel);
        majorPanel.add(majorSnapshotBtn);

        //次版本
        JPanel minorPanel = new JPanel();
        JLabel minorTag = new JLabel("次版本：");
        minorTag.setPreferredSize(new Dimension(100,30));
        minorTag.setHorizontalAlignment(SwingConstants.CENTER);

        this.minorMasterLabel = new EditorTextField("");
        this.minorMasterLabel.setPreferredSize(new Dimension(130,30));

        JButton minorMasterBtn = new JButton("应用");
        minorMasterBtn.setPreferredSize(new Dimension(70,30));
        minorMasterBtn.addActionListener(e->{
            saveVersion(this.minorMasterLabel.getText());
        });

        this.minorSnapshotLabel = new EditorTextField();
        this.minorSnapshotLabel.setPreferredSize(new Dimension(130,30));

        JButton minorSnapshotBtn = new JButton("应用");
        minorSnapshotBtn.setPreferredSize(new Dimension(70,30));
        minorSnapshotBtn.addActionListener(e->{
            saveVersion(this.minorSnapshotLabel.getText());
        });

        minorPanel.add(minorTag);
        minorPanel.add(this.minorMasterLabel);
        minorPanel.add(minorMasterBtn);
        minorPanel.add(this.minorSnapshotLabel);
        minorPanel.add(minorSnapshotBtn);

        //修正版本
        JPanel revisedPanel = new JPanel();
        JLabel revisedTag = new JLabel("修正版本：");
        revisedTag.setPreferredSize(new Dimension(100,30));
        revisedTag.setHorizontalAlignment(SwingConstants.CENTER);

        this.revisedMasterLabel = new EditorTextField("");
        this.revisedMasterLabel.setPreferredSize(new Dimension(130,30));

        JButton revisedMasterBtn = new JButton("应用");
        revisedMasterBtn.setPreferredSize(new Dimension(70,30));
        revisedMasterBtn.addActionListener(e->{
            saveVersion(this.revisedMasterLabel.getText());
        });

        this.revisedSnapshotLabel = new EditorTextField();
        this.revisedSnapshotLabel.setPreferredSize(new Dimension(130,30));

        JButton revisedSnapshotBtn = new JButton("应用");
        revisedSnapshotBtn.setPreferredSize(new Dimension(70,30));
        revisedSnapshotBtn.addActionListener(e->{
            saveVersion(this.revisedSnapshotLabel.getText());
        });

        revisedPanel.add(revisedTag);
        revisedPanel.add(this.revisedMasterLabel);
        revisedPanel.add(revisedMasterBtn);
        revisedPanel.add(this.revisedSnapshotLabel);
        revisedPanel.add(revisedSnapshotBtn);
        getSouthPanel(url,artifactIdValue);
        southPanel.add(titlePanel);
        southPanel.add(curPanel);
        southPanel.add(referencePanel);
        southPanel.add(majorPanel);
        southPanel.add(minorPanel);
        southPanel.add(revisedPanel);
        jPanel.add(southPanel,BorderLayout.SOUTH);
        return jPanel;
    }

    private void getSouthPanel(String url,String artifactId){
        if(StringUtils.isBlank(url) || StringUtils.isBlank(artifactId)){
            return;
        }
        if(!url.endsWith("/")){
            url =url+"/";
        }
        String jsonData = "{\"action\": \"coreui_Search\", \"method\": \"read\", " +
                "\"data\": [{\"page\": 1, \"start\": 0, \"limit\": 300, \"sort\":" +
                " [{\"property\": \"version\", \"direction\": \"DESC\"}]," +
                "\"filter\": [{\"property\": \"attributes.maven2.artifactId\", \"value\": \""+
            artifactId+"\"}]}], \"type\": \"rpc\", \"tid\": 1}";

        String reult  = null;
        try{
            WorkSpaceXmlHandler.addMavenRepository(CommonData.workSpacePath,url);
        }catch (Exception e){
            NoticUtils.sendNotice("无效的maven仓库地址！",MessageType.ERROR);
        }
        if(url.startsWith("https") || url.startsWith("HTTPS")){
            reult =HTTPTools.postIgnoreSSl(url+"service/extdirect",jsonData,"UTF-8");
        }else{
            reult =HTTPTools.post(url+"service/extdirect",jsonData,"UTF-8");
        }
        Map<String,String> map = new HashMap<>();
        try{
            map = getVersionByResult(reult);
        }catch (Exception e){
            NoticUtils.sendNotice("无效的maven仓库地址！\n返回结果:"+reult+"。",MessageType.ERROR);
        }
        String masterVer = map.containsKey("master")?map.get("master"):"";
        String snapshotVer = map.containsKey("snapshots")?map.get("snapshots"):"";
        this.masterLabel.setText(masterVer);
        this.snapshotLabel.setText(StringUtils.isNotBlank(snapshotVer)?snapshotVer+"-SNAPSHOT":"");
        if(StringUtils.isNotBlank(masterVer)){
            this.majorMasterLabel.setText(getNewVersion(masterVer,1,true));
            this.minorMasterLabel.setText(getNewVersion(masterVer,2,true));
            this.revisedMasterLabel.setText(getNewVersion(masterVer,3,true));
        }

        if(StringUtils.isNotBlank(snapshotVer)){
            this.majorSnapshotLabel.setText(getNewVersion(snapshotVer,1,false));
            this.minorSnapshotLabel.setText(getNewVersion(snapshotVer,2,false));
            this.revisedSnapshotLabel.setText(getNewVersion(snapshotVer,3,false));
        }
    }

    private void saveVersion(String version){
        PomXmlHandler.setArtifactId(CommonData.pomPath,version);
    }

    private String getNewVersion(String version,int num,boolean isMaster){
        String [] arr =version.split("\\.");
        if(arr.length >=num){
            String [] newArr = new String[arr.length];
            for(int i =0;i<newArr.length;i++){
                if(i<(num-1)){
                    newArr[i] = arr[i];
                }else if(i==(num-1)){
                    Integer newNum = Integer.parseInt(arr[i])+1;
                    newArr[i] =newNum+"";
                }else{
                    newArr[i] ="0";
                }
            }
            return StringUtils.join(newArr,".")+(isMaster?"":"-SNAPSHOT");
        }else{
            return "";
        }
    }

    private Map<String,String> getVersionByResult(String result){
        JSONObject root = JSONObject.parseObject(result);
        if(Objects.isNull(root)){
            return null;
        }
        JSONObject resultObj = root.getJSONObject("result");
        if(Objects.isNull(resultObj)){
            return null;
        }
        JSONArray data = resultObj.getJSONArray("data");
        if(Objects.isNull(data) || data.size() ==0){
            return null;
        }
        Map<String,String> resultMap = new HashMap<>();
        for (int i =0 ;i<data.size() ;i++){
            JSONObject item =data.getJSONObject(i);
            if(Objects.isNull(item)){
                continue;
            }
            String repositoryName = item.getString("repositoryName");
            if(StringUtils.isBlank(repositoryName)){
                continue;
            }
            String version = item.getString("version");
            if(StringUtils.isBlank(version)){
                continue;
            }
            //releases\snapshots
            if(!"releases".equalsIgnoreCase(repositoryName)){
                version = version.substring(0,version.indexOf("-"));
                if(!resultMap.containsKey("snapshots")){
                    resultMap.put("snapshots",version);
                }else{
                    resultMap.put("snapshots",compareVersion(resultMap.get("snapshots"),version));
                }
            }else {
                if(!resultMap.containsKey("master")){
                    resultMap.put("master",version);
                }else{
                    resultMap.put("master",compareVersion(resultMap.get("master"),version));
                }
            }
        }
        return resultMap;
    }

    private String compareVersion(String oldVersion,String newVersion){
        String [] oldArr = oldVersion.split("\\.");
        String [] newArr = newVersion.split("\\.");
        int minLength = oldArr.length > newArr.length ? newArr.length : oldArr.length;
        for (int i =0 ;i<minLength;i++){
            if(Integer.parseInt(oldArr[i])<Integer.parseInt(newArr[i])){
                return newVersion;
            }else if(Integer.parseInt(oldArr[i])>Integer.parseInt(newArr[i])){
                return oldVersion;
            }
        }
        if(oldArr.length>minLength){
            return oldVersion;
        }else{
            return newVersion;
        }
    }

    @Override
    protected JComponent createSouthPanel() {
        JPanel jPanel = new JPanel();
        JButton colseBtn = new JButton("关闭");
        colseBtn.addActionListener(e->{
            this.close(0);
        });
        jPanel.add(colseBtn);
        return jPanel;
    }
}
